import Vue from 'vue'

import App from './App'

// vuex
import store from './store'

// 引入全局uView
import uView from '@/uni_modules/uview-ui'

import mixin from './common/mixin'



import moxiConfig from "@/moxiConfig.js"
Vue.prototype.moxiInfo = {
	show:true,
	requestParam:{
		moxi_pageid:""
	},
	kefuMsg:0,//客服插件消息
}
Vue.prototype.$store = store

Vue.config.productionTip = false

App.mpType = 'app'
Vue.use(uView)


Vue.mixin(require('@/moxi/mixin/init.js'))
Vue.mixin(mixin)


Vue.prototype.moxi = {
	appid: 0,
	module: 0,
	length(ar) {
		let num = 0;
		for (let k in ar) {
			num++;
		}
		return num;
	},
	background(style) { //处理背景色，可以是数组或字符串
		let background = '';
		if (style.length) {
			if (Array.isArray(style)) {
				if (style.length == 1) {
					style.push(style[0])
				}
				background = 'background: linear-gradient(to right';
				for (let k in style) {
					background += ',' + style[k];
				}
				background += ');';
			} else {
				background += 'background-color:' + style + ';';
			}
		}
		return background;
	},
	copy(data) {
		return JSON.parse(JSON.stringify(data))
	}
}

//当前页面的信息
Vue.prototype.$pageData = {
	curPageName: "",
	param: {},
	navHeight: 0,
	
}

//请求缓存
Vue.prototype.$appData = {
	appid: false,
	init:false,
	module: "",
	data: {},
	userinfo: {},
	reuid: false,
	plugin: {},
	kefu_token:"",
	unread:0,//客服插件未读消息数量
	code:"",//使用表单组件获取验证码
	app_type:"",//应用类型
	
}
Vue.prototype.$moxiData = {
	loginBox:true
};

/**
* 获取坐标，返回参数如下【此函数会优先获取缓存信息】
accuracy: 65
errMsg: "getLocation:ok"
horizontalAccuracy: 65
latitude: 23.00944
longitude: 113.12249
speed: -1
verticalAccuracy: 65
 */
Vue.prototype.moxiGetLocation = function(call = ()=>{}){
	
	const data = this.cache('moxiGetLocation');
	if(data&&data.latitude){
		call(data);
		return;
	}
	let self = this;
	uni.getLocation({
		type: 'gcj02',
		success: function (res) {
			// console.log('定位成功');
			
			self.cache('moxiGetLocation',res,60*60*24)
			call(res)
		}, 
		fail(res) {
			if(res.errMsg){
				self.msg(res.errMsg)
			}
			console.log('定位失败',res);
			call({})
		},complete() {
			// console.log('定位');
		}
	});
}

//通用缓存设置【同步】
Vue.prototype.cache = function(name, data = null, time = 0){
	const curTime = new Date().getTime();//精确到毫秒
	if(data===null){
		let info = uni.getStorageSync(name)
		if(info&&info.data){
			if(info.expire>0&&info.expire<curTime){
				uni.removeStorageSync(name);
				return false;
			}else{
				return info.data;
			}
		}else{
			return false;
		}
	}else{
		return uni.setStorageSync(name, {
			expire:time==0?0:curTime+(time*1000),
			data:data
		});
	}
}

//缓存操作，单独针对每个appid和每个module
Vue.prototype.moxiCache = function(name, data = null, Sync = true) {
	name = 'mx_a_' + this.moxiConfig('appid') + '_m_' + this.moxiConfig('module') + '_' + name;
	if (data !== null) {
		if (Sync) {
			uni.setStorageSync(name, data);
		} else {
			uni.setStorage({
				key: name,
				data: data
			})
		}

	} else {
		return uni.getStorageSync(name);
	}
}


Vue.prototype.setModule = function(id) { //动态设置Module
	const module = this.moxiConfig('module');
	if (id == module) {
		return true;
	}
	const res = uni.getStorageInfoSync();
	if (!res) {
		return;
	}
	for (let k in res.keys) {
		if (res.keys[k].indexOf('mx_a_' + this.moxiConfig('appid') + "m_" + module) === 0) {
			uni.removeStorageSync(res.keys[k]);
		}
	}
	this.moxi.module = id;
	moxiConfig.module = id;
	uni.setStorageSync('mx_module', id);
	this.$appData = {
		appid: false,
		module: "",
		data: {},
		userinfo: this.$appData.userinfo,
		reuid: this.$appData.reuid,
		plugin: {},
		loginBox:false
	}
	
	this.$pageData = {
		curPageName: "",
		param: {},
		navHeight: 0
	}
	return true;
}

//动态设置appid
Vue.prototype.setAppid = function(id) {
	const curAppid = this.moxiConfig('appid');
	if (id == curAppid) {
		return true;
	}
	const res = uni.getStorageInfoSync();
	if (!res) {
		return;
	}
	for (let k in res.keys) {
		if (res.keys[k].indexOf('mx_appid_' + curAppid) === 0) {
			uni.removeStorageSync(res.keys[k]);
		}
	}
	this.moxi.appid = id;
	moxiConfig.appid = id;
	uni.setStorageSync('mx_appid', id);
	this.$appData = {
		appid: false,
		module: "",
		data: {},
		userinfo: this.$appData.userinfo,
		reuid: this.$appData.reuid,
		plugin: {},
		loginBox:false
	}
	this.$pageData = {
		curPageName: "",
		param: {},
		navHeight: 0
	}
	return true;
}
//获取配置信息
Vue.prototype.moxiConfig = function(key = null) {

	//下面是修改后的，实时获取APPID，不再获取缓存
	let appid = moxiConfig.appid;
	//#ifdef MP-WEIXIN
	let extConfig = wx.getExtConfigSync ? wx.getExtConfigSync() : {}
	if (extConfig.moxiappid) {
		appid = extConfig.moxiappid;
		moxiConfig.domain = extConfig.domain;
	}
	//#endif
	moxiConfig.appid = appid;
	this.moxi.appid = appid;
	//截止
	
	if (this.moxi.module === 0) {
		let module = uni.getStorageSync('mx_module');
		if (!module) {
			module = moxiConfig.module;
			uni.setStorage({
				key: 'mx_module',
				data: module
			});
		}
		moxiConfig.module = module;
		this.moxi.module = module;
	}


	if (key !== null && key) {
		return moxiConfig[key];
	}
	return moxiConfig;

}


Vue.prototype.loginBox = function(type='phone'){
	let self = this;
	let tm = setTimeout(()=>{
		if(self.$refs.moxinav){
			self.$refs.moxinav.show(type)
		}else{
			let tm = setTimeout(()=>{
				self.$refs.moxinav.show(type)
				clearTimeout(tm)
				},500)
		}
		clearTimeout(tm)
	},500)
}



Vue.prototype.msg = function(text = '', type = 'warning') {
	let self = this;
	let tm = setTimeout(()=>{
		uni.showToast({
			title: text,
			duration: 2500,
			icon:"none"
		});
		clearTimeout(tm)
	},120)
}
//获取用户信息
Vue.prototype.getUserInfo = function() {
	if (!this.$appData.userinfo || !this.$appData.userinfo.id) {
		this.$appData.userinfo = uni.getStorageSync('userinfo');
	}
	if (!this.$appData.userinfo || !this.$appData.userinfo.id) {
		return false;
	} else {
		return this.$appData.userinfo;
	}
}
//获取随机字符串
Vue.prototype.randomString = function(length=32){
	var str = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
	var result = '';
	for (var i = length; i > 0; --i)
		result += str[Math.floor(Math.random() * str.length)];
	return result;
}

Vue.prototype.requestParam = function(param) {
	let moxi_device = this.moxiCache('moxi_device');
	if(!moxi_device){
		moxi_device = this.randomString(19)+String(new Date().getTime())
		this.moxiCache('moxi_device',moxi_device);
	}
	let config = this.moxiConfig();
	let defaultParam = {
		is_app: 1,
		app_type: config['appType'],
		moxi_appid: config.appid,
		s_d: config.module,
	}

	param = Object.assign(defaultParam, param);
	param.moxi_device = moxi_device;
	const userinfo = this.getUserInfo();
	const reuid = Number(uni.getStorageSync('reuid'));
	param.reuid = reuid;
	if (userinfo) {
		param.user_id = userinfo.id;
		param.user_token = userinfo.user_token;
		param.reuid = param.user_id; //登录后reuid为当前用户ID
	}
	param.moxi_pageid = this.moxiInfo.requestParam.moxi_pageid;
	return param;
}


//获取地址缓存
Vue.prototype.getAddress = function(callback){
	let cityList = uni.getStorageSync('cityListInfo');
	if(cityList){
		callback(cityList)
	}else{
		this.moxiPost('/index/tools/city',function (data) {
			uni.setStorage({
				key:'cityListInfo',
				data:data.data
			})
			callback(data.data)
		})
	}
}


/**
 * 计算距离
 * @param {Object} lat1 当前la
 * @param {Object} lon1 当前ln
 * @param {Object} lat2 目标la
 * @param {Object} lon2 目标ln
 */
Vue.prototype.getDistance = function(lat1, lon1, lat2, lon2,km = true){
	lat1 = Number(lat1);
	lon1 = Number(lon1);
	lat2 = Number(lat2);
	lon2 = Number(lon2);
	// 使用 Vincenty 公式计算距离
	const a = 6378137; // 地球长半轴（米）
	const f = 1 / 298.257223563; // 地球扁率
	const b = (1 - f) * a;
	const L = (lon2 - lon1) * (Math.PI / 180);
	const U1 = Math.atan((1 - f) * Math.tan(lat1 * (Math.PI / 180)));
	const U2 = Math.atan((1 - f) * Math.tan(lat2 * (Math.PI / 180)));
	let sinU1 = Math.sin(U1), cosU1 = Math.cos(U1);
	let sinU2 = Math.sin(U2), cosU2 = Math.cos(U2);
	let lambda = L;
	let lambdaP;
	let iterLimit = 100;
	let cosSqAlpha;
	let cosSigma;
	let sigma;
	let sinAlpha;
	let sinLambda;
	let cosLambda;
	let sinSigma;
	let cos2SigmaM;
	do {
	     sinLambda = Math.sin(lambda);
	     cosLambda = Math.cos(lambda);
	     sinSigma = Math.sqrt((cosU2 * sinLambda) * (cosU2 * sinLambda) +
	        (cosU1 * sinU2 - sinU1 * cosU2 * cosLambda) * (cosU1 * sinU2 - sinU1 * cosU2 * cosLambda));
	    if (sinSigma === 0) {
	        return 0; // 两点重合
	    }
	     cosSigma = sinU1 * sinU2 + cosU1 * cosU2 * cosLambda;
	     sigma = Math.atan2(sinSigma, cosSigma);
	     sinAlpha = cosU1 * cosU2 * sinLambda / sinSigma;
	     cosSqAlpha = 1 - sinAlpha * sinAlpha;
	     cos2SigmaM;
	    if (cosSqAlpha!== 0) {
	        cos2SigmaM = cosSigma - 2 * sinU1 * sinU2 / cosSqAlpha;
	    } else {
	        cos2SigmaM = 0;
	    }
	    const C = f / 16 * cosSqAlpha * (4 + f * (4 - 3 * cosSqAlpha));
	    lambdaP = lambda;
	    lambda = L + (1 - C) * f * sinAlpha *
	        (sigma + C * sinSigma * (cos2SigmaM + C * cosSigma * (-1 + 2 * cos2SigmaM * cos2SigmaM)));
	} while (Math.abs(lambda - lambdaP) > 1e-12 && --iterLimit > 0);
					
	if (iterLimit === 0) {
	    return NaN; // 迭代未收敛
	}
					
	const uSq = cosSqAlpha * (a * a - b * b) / (b * b);
	const A = 1 + uSq / 16384 * (4096 + uSq * (-768 + uSq * (320 - 175 * uSq)));
	const B = uSq / 1024 * (256 + uSq * (-128 + uSq * (74 - 47 * uSq)));
	const deltaSigma = B * sinSigma * (cos2SigmaM + B / 4 * (cosSigma * (-1 + 2 * cos2SigmaM * cos2SigmaM) -
	    B / 6 * cos2SigmaM * (-3 + 4 * sinSigma * sinSigma) * (-3 + 4 * cos2SigmaM * cos2SigmaM)));
	let s = b * A * (sigma - deltaSigma);
	if(!km){
		return s;
	}
	s = s / 1000; // 转换为公里
	s = Math.round(s * 10000) / 10000;
	s = s.toString();
	s = s.substring(0, s.indexOf('.') + 2);
	return s;//公里
}


/**
 * 上传文件
 * url是上传文件地址
 * 携带参数【参数会通过url传递】
 */
Vue.prototype.moxiUpload = function(url, callback, fileType = 'image', loading = true) {
	let self = this;
	let urlParam = '';
	let param = this.requestParam({});
	for (let k in param) {
		urlParam += '&' + k + '=' + param[k]
	}
	urlParam = this.moxiConfig('domain') + '/api/upimg/upimg?' + urlParam.substr(1);
	if (loading) {
		uni.showLoading({
			title: '加载中'
		});
	}
	param = this.requestParam(param);
	uni.uploadFile({
		url: urlParam,
		filePath: url,
		fileType: fileType,
		name: 'file',
		success: (data) => {
			
			let pic = '';
			// #ifndef MP-BAIDU
			data.data = JSON.parse(data.data);
			// #endif
			if(data.data.result){
				if(data.data.result==999){
					self.toLogin();return;
				}else if(data.data.result>1){
					self.msg(data.data.hint);return;
				}
			}
			
			pic = data.data.data;
			callback(pic)
		},
		fail(res) {
			console.log(res);
		},
		complete(data) {
			if (loading) {
				uni.hideLoading();
			}
		}
	})
}
Vue.prototype.moxiGet = function(url,call,loading=false){
	uni.request({
		url: this.moxiConfig('domain') + url,
		method: "GET",
		header: {
			'content-type': 'application/x-www-form-urlencoded',
		},
		success: (res) => {
			call && call(res)
			
		},
		fail: (err) => {
			console.log(err);
			uni.showToast({
				icon: "none",
				title: 'get网络请求异常'+this.moxiConfig('domain') + url,
				duration: 2000
			});
		},
		complete(data) {
			if (loading) {
				uni.hideLoading();
			}
		}
	})
}

Vue.prototype.moxiPost = function(url, param, callback, loading = true) {
	let self = this;
	if (!callback) {
		callback = param;
		param = {}
	}
	param = this.requestParam(param);

	if (loading) {
		uni.showLoading({
			title: '加载中'
		});
	}
// console.log(param);
	uni.request({
		url: this.moxiConfig('domain') + url,
		method: "POST",
		header: {
			'content-type': 'application/x-www-form-urlencoded',
		},
		data: {
			moxiPostData: JSON.stringify(param)
		},
		success: (res) => {
			if (res.data.userData) { //保存用户信息
				uni.setStorageSync('userinfo', res.data.userData);
			}
			if (res.data.moxi_pageid) { //保存moxi_pageid
				self.moxiInfo.requestParam.moxi_pageid = res.data.moxi_pageid;
			}
			if (res.data.result == 1) {
				callback(res.data)
			} else if (res.data.result == 999) {
				self.$appData.userinfo = null;
				uni.removeStorageSync('userinfo');
				self.toLogin();
				return false;
			} else {
				// console.log(res);
				self.msg(res.data.hint)
			}
			
		},
		fail: (err) => {
			console.log(err);
			uni.showToast({
				icon: "none",
				title: '请求异常：'+param.moxi_appid+"/"+this.moxiConfig('domain') + url,
				duration: 2000
			});
		},
		complete(data) {
			if (loading) {
				uni.hideLoading();
			}
		}
	})
}

//跳转到登录页
Vue.prototype.toLogin = function(){
	
	let curpageInfo = getCurrentPages();
	curpageInfo = curpageInfo[curpageInfo.length - 1];
	// console.log(curpageInfo.$page);
	
	curpageInfo = encodeURIComponent(curpageInfo.$page.fullPath);
	
	uni.redirectTo({
		url: '/page_user/login/login?page=' + curpageInfo
	});
}

//获取当前完整地址
Vue.prototype.get_cur_page = function(currentRoutes = undefined) {
	if(!currentRoutes){
		currentRoutes = getCurrentPages(); // 获取当前打开过的页面路由数组
	}
	let path;
	if(currentRoutes[currentRoutes.length - 1].$page&&currentRoutes[currentRoutes.length - 1].$page.fullPath){
		if(currentRoutes[currentRoutes.length - 1].$page.fullPath.indexOf("/") === 0){
			currentRoutes[currentRoutes.length - 1].$page.fullPath = currentRoutes[currentRoutes.length - 1].$page.fullPath.substr(1);
		}
		path = currentRoutes[currentRoutes.length - 1].$page.fullPath;
	}else{
		let currentRoute = currentRoutes[currentRoutes.length - 1].route //获取当前页面路由
		let currentParam = currentRoutes[currentRoutes.length - 1].options; //获取路由参数
		
		// 拼接参数
		let param = ''
		for (let key in currentParam) {
			param += '?' + key + '=' + currentParam[key]
		}
		path = currentRoute + param;
	}
	if (path.startsWith('/')) {
		path =  path.substring(1);
	}
	return path;
}

Vue.prototype.getParam = function(url, name = null) {
	var pms = {};
	if (url.indexOf('?') != -1) {
		var temp1 = url.split('?');
		var pram = temp1[1];
		var keyValue = pram.split('&');
		for (var i = 0; i < keyValue.length; i++) {
			var item = keyValue[i].split('=');
			var key = item[0];
			var value = item[1];
			if (key) {
				if (value === undefined) {
					value = '';
				}
				pms[key] = value;
			}
		}
	}
	if (name !== null) {
		if (pms[name]) {
			return pms[name];
		} else {
			return ""
		}
	}
	return pms;
}

//确认窗口
Vue.prototype.isBox = (title,call,text='',cancel)=>{
	uni.showModal({
		title: title,
		content: text,
		success: function (res) {
			if (res.confirm) {
				call()
			} else if (res.cancel) {
				cancel&&cancel()
				// console.log('用户点击取消');
			}
		}
	});
} 

/**
 * 跳转页面
 * 如果指定appid或指定module则会自动切换并关掉所有页面后跳转
 */
Vue.prototype.navto = function(url, close = false, appid = false, module = false) {

	if(url==='index'){
		url = 'pages/index/index'
	}
	// console.log(url);
	var pages = getCurrentPages(); // 获取当前页面栈
	var currentPage = pages[pages.length - 1]; // 获取当前页面
	if (url == '' || url == this.get_cur_page(pages)) {
		return false;
	}
	
	if (url.indexOf('tel?') == 0) {
		uni.makePhoneCall({
			phoneNumber: this.getParam(url, 'tel')
		});
		return;
	}else if (url.indexOf("open_mp?") == 0) {
		const appId = this.getParam(url, 'appId');
		let ph = this.getParam(url, 'path');
		if(ph.length){
			ph = decodeURIComponent(ph);
			if(ph.length&&ph.indexOf("/")!==0){
				ph = '/'+ph;
			}
		}
		if(appId&&appId.length){
			let self = this;
			uni.navigateToMiniProgram({
			  appId: appId,
			  path: ph.length?ph:'',
			  success(res) {
			    self.msg("跳转成功！")
			  }
			})
		}
	} else if (url.indexOf("clear_cache?") == 0) {
		if (this.getParam(url, 'type') == 'y') {
			uni.clearStorage();
			this.msg('操作成功')
			this.moxiPost('/index/user/loginout',{},()=>{})
		} else {
			const res = uni.getStorageInfoSync();
			for (let k in res.keys) {
				if (res.keys[k] != 'userinfo') {
					uni.removeStorageSync(res.keys[k]);
					this.msg('操作成功')
				}
			}
		}
		return;
	} else if (url.indexOf("open_map?") == 0) {
		let obj = this.getParam(url)
		let info = JSON.parse(obj.map)
		
		if (info && info.center && info.center[1]) {
			uni.openLocation({
				latitude: info.center[1],
				longitude: info.center[0],
				name: obj.name,
				address: info.address,
				success: function() {

				}
			});
		} else {
			this.msg('未设置地图')
		}
		return;
	}

	// #ifdef H5

	if(pages.length>=3){//h5当页面栈超过3个时就清空跳转
		close = true;
	}
	let platform = uni.getSystemInfoSync().platform;

	if(url.indexOf(currentPage.route)>-1){
		var currentUrl = window.location.href;
		const arr = currentUrl.split("#");
		if(arr[1]){
			window.location.href = arr[0]+'#/'+url
			if(platform=='ios'){
				
				location.reload();
			}
			return;
		}
	}else if (url.indexOf("http") == 0) {
		window.location.href = url;
		if(platform=='ios'){
			location.reload();
		}
		return;
	}
	
	// #endif
	
	if(pages.length>=8){//除h5当页面栈超过8个时就清空跳转
		close = true;
	}
	
	if (url.indexOf("/") !== 0) {
		url = "/" + url;
	}
		
	if (appid || module) {
		let s = false; //是否切换
		if (appid) {
			if (this.setAppid(appid)) {
				s = true;
			}
		}
		if (module) {
			if (this.setModule(module)) {
				s = true;
			}
		}
		if (s) {
			uni.reLaunch({
				url: url
			});
			return;
		}
	}
	if (close) { //关掉所有页面跳转
		uni.redirectTo({
			url: url
		});
	} else { //直接跳转
		uni.navigateTo({
			url: url
		});
	}

}

// Vue.prototype.getCity = function(obj) {
// 	this.moxiPost('/index/tools/city', obj, function(data) {
// 		console.log('data ==>', data);
// 	})
// }




const app = new Vue({
	store,
	...App
})

// 引入请求封装
require('./util/request/index')(app)

app.$mount()